package com.cloud.flowable.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cloud.common.constants.FlowTaskConstants;
import com.cloud.exception.CustomException;
import com.cloud.flowable.entity.WfFormTest;
import com.cloud.entity.vo.TaskParam;
import com.cloud.flowable.mapper.WfFormTestMapper;
import com.cloud.flowable.service.IWfFormTestService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.flowable.service.IWfProcessService;
import com.cloud.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 流程表单测试表
 *
 * @author yzj
 * @since 2024-02-26
 */
@Service
public class WfFormTestServiceImpl extends ServiceImpl<WfFormTestMapper, WfFormTest> implements IWfFormTestService {

    @Resource
    private WfFormTestMapper wfFormTestMapper;

    @Autowired
    private IWfProcessService processService;

    /**
     * 流程表单测试表列表xinjian
     */
    @Override
    public List<WfFormTest> getWfFormTestList(WfFormTest wfFormTest) {
        return wfFormTestMapper.getWfFormTestList(wfFormTest);
    }

    /**
     * 流程表单测试表新增
     */
    @Override
    public int saveWfFormTest(WfFormTest wfFormTest) {
        TaskParam taskParam = new TaskParam();
        taskParam.setProcDefKey(wfFormTest.getProcessKey());
        Map<String, Object> variables = new HashMap<>();
        variables.put(wfFormTest.getNodeKey(), wfFormTest);
        taskParam.setVariables(variables);
        // 根据流程标识,启动流程实例
        wfFormTest.setProcInsId(processService.startProcByDefKey(taskParam));
        return wfFormTestMapper.insert(wfFormTest);
    }

    /**
     * 流程表单测试表修改
     */
    @Override
    public int editWfFormTest(JSONObject param) {
        WfFormTest formTest = param.getObject(FlowTaskConstants.PARAM_VALUE, WfFormTest.class);
        if (StringUtils.isNull(formTest)) {
            throw new CustomException("操作失败:获取流程表单数据失败");
        }
        UpdateWrapper<WfFormTest> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("proc_ins_id", param.getString(FlowTaskConstants.PARAM_KET));
        return wfFormTestMapper.update(formTest, updateWrapper);
    }

    /**
     * 流程表单测试表删除
     */
    @Override
    public int removeIds(List<Long> ids) {
        return wfFormTestMapper.deleteBatchIds(ids);
    }

}
